<!--  -->
<template>
  <div>
    <el-form
      :label-position="labelPosition"
      label-width="80px"
      :model="form"
      :rules="rules"
      ref="form"
    >
      <el-upload
        ref="upload"
        class="avatar-uploader"
        action="http://127.0.0.1:3006/api/loadImg"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-error="handleErrR"
        :on-progress="uploadVideoProcess"
        name="avatar123"
      >
        <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <!-- 进度条 (加动漫)-->
      <transition
        name="animate__animated animate__bounce"
        enter-active-class="animate__fadeIn"
        leave-active-class="animate__fadeOutUp"
      >
        <el-progress
          type="line"
          v-if="progressFlag"
          :percentage="percent"
        ></el-progress>
      </transition>

      <el-form-item label="账号" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>

      <el-button type="primary" @click="submitForm()">提交</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form>
  </div>
</template>

<script>
import request from "../util/request";
import animate from "animate.css";
export default {
  name: "formTest",
  data() {
    return {
      labelPosition: "right",
      form: {
        name: "",
        password: "",
        imageUrl: "",
      },
      percent: 0,
      progressFlag: false,
      rules: {
        name: [
          { required: true, message: "用户名不可为空", trigger: "blur" }, //blur表示失去焦点时校验
          { type: "string", message: "用户名必须字符串", trigger: "blur" },
          { whitespace: true, message: "不可全为空格", trigger: "blur" },
          { min: 6, max: 10, message: "长度6-10", trigger: "blur" },
          // { min: 6, max: 10, message: "长度6-10", trigger: ["change", "blur"] },
        ],
        password: [
          { required: true, message: "密码不可为空", trigger: "blur" }, //blur表示失去焦点时校验
          { min: 6, max: 10, message: "长度6-10", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //上传之前 限制大小、图片格式
    beforeAvatarUpload(file) {
      console.log("beforeAvatarUpload", file);
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size < 1024 * 1024 * 2; //小于2M
      console.log(isJPG);
      if (!isJPG) {
        alert("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        alert("上传头像图片大小不能超过 2MB !");
      }
      return isJPG && isLt2M;
    },
    //上传过程（进度条）
    uploadVideoProcess(event, file, fileList) {
      this.progressFlag = true; //显示进度条
      this.percent = event.percent;
      if (this.percent >= 100) {
        setTimeout(() => {
          this.progressFlag = false; //隐藏进度条
        }, 1000);
      }
    },
    //上传成功 获得后端res 可以替换图片
    handleAvatarSuccess(res, file) {
      console.log("res", res);
      this.form.imageUrl = res.imgUrl;
    },
    //上传失败
    handleErrR(err, file, fileList) {
      // console.warn(err, file, fileList);
      console.warn("上传失败");
    },
    //提交检测
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //添加数据入fd
          let fd = new FormData();
          Object.keys(this.form).forEach((key) => {
            fd.append(key, this.form[key]);
          });

          request({
            method: "post",
            url: "http://localhost:3006/api/loadImg",
            data: fd,
          }).then(
            (res) => {
              console.log(res.data);
            },
            (err) => {
              console.log(err);
            }
          );
        }
      });
    },
    // 表单重置
    resetForm() {
      this.$refs["form"].resetFields();
    },
  },
};
</script>

<style scoped>
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
